# -*- coding: utf-8 -*-

'''eof
name:最近3M未订烟周期数/应订烟周期数占比（LT）
code:Mon3PeriodsSituation_LT
tableName:
columnName:
groups:烟商
dependencies:BTM
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
1.计算最近90天的应订烟周期数： 
应订烟周期数 = 90/订货周期； 
2.计算最近90天的订烟周期数： 
indentNum 订单编号
Select count(订单编号) as 实际订烟周期数 from 订单数组 where 订单总金额 ≠ null and 当前日期 - 订单日期 ≤90; 
3.Factor = （应订烟周期数 - 实际订烟周期数）/应订烟周期数 
注：如果该客户有规范格式的“订货周期”原始数据，
即抓取该数据作为计算“订货周期”的字段；否则将“订货周期”统一设为7天计算
'''

import sys
import pandas as pd
import datetime
import re

reload(sys)
sys.setdefaultencoding('utf-8')


def Mon3PeriodsSituation_LT():
    null_type_list = ['',None,'null','Null','/', ' ']
    indent_num = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_days_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [90, 0]]
        else:
            last_year_days_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [90, 0]]
    except:
        return u'缺失值'

    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and BTM_.has_key('periods') and len(BTM_['indent']) >= 1:
            if BTM_['periods'] not in null_type_list:
                periods_list = BTM_['periods'].split(':')
                if len(periods_list) == 2 and periods_list[0].isdigit() and periods_list[1].isdigit():
                    periods = float(periods_list[0])
                else:
                    periods = float(7)
            else:
                periods = float(7)
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                    and i.has_key('indentMoney') and i['indentMoney'] not in null_type_list \
                    and isfloat(i['indentMoney']) \
                    and Formate(i['indentDate']) is not None \
                    and i.has_key('indentNum') and i['indentNum'] not in null_type_list\
                    and Formate(i['indentDate']) > last_year_days_list[0] \
                        and Formate(i['indentDate']) <= last_year_days_list[1]:
                    #以订单编号indentNum计数
                    indent_num.append(i['indentNum'])
            sj_periods = float(len(indent_num))
            if periods != float(0):
                yd_periods = float(90)/periods
                return round(float((yd_periods-sj_periods)/yd_periods), 4)
            else:
                return u'缺失值'
        else:
            return u'缺失值'
    except:
        return u'缺失值'

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            return True
        else:
            return False
    except:
        return False

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

result = Mon3PeriodsSituation_LT()